#!/usr/bin/env python3
import json
import sys

def fix_coefficients(json_file):
    """修正Monet协议中的系数错误"""
    
    # 定义需要修正的地址范围和对应的系数
    coefficient_fixes = {
        # 储能侧参数 (1884-1899)
        (1884, 1895): 1000,  # 电压、电流、功率
        (1896, 1898): 5000,  # 频率 (对应50.00Hz)
        1899: 100,  # 功率因数
        
        # 电网侧参数 (1900-1915)
        (1900, 1905): 1000,  # 电压、电流
        (1906, 1908): 5000,  # 频率
        1909: 100,  # 功率因数
        (1910, 1912): 1000,  # 功率
        (1913, 1915): 1000,  # AC模块直流参数
        
        # 环境参数
        1916: 100,  # 温度
        1917: 100,  # 湿度
        
        # 电池参数
        (1918, 1919): 10,  # 温度
        (1920, 1923): 1000,  # 电压、电流
        1924: 100,  # SOC
        1925: 100,  # SOH
        
        # DC模块参数
        (1928, 1939): 1000,  # 所有DC模块参数
    }
    
    # 读取JSON文件
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 修正系数
    fixed_count = 0
    for point in data.get('data_points', []):
        address = point.get('address')
        if address:
            new_coefficient = None
            
            # 检查地址是否需要修正
            for key, value in coefficient_fixes.items():
                if isinstance(key, tuple):
                    if key[0] <= address <= key[1]:
                        new_coefficient = value
                        break
                elif key == address:
                    new_coefficient = value
                    break
            
            # 如果需要修正且当前系数不正确
            if new_coefficient and point.get('coefficient') != new_coefficient:
                old_coefficient = point.get('coefficient')
                point['coefficient'] = new_coefficient
                fixed_count += 1
                print(f"修正地址 {address}: 系数从 {old_coefficient} 改为 {new_coefficient}")
    
    # 写回文件
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    print(f"\n总共修正了 {fixed_count} 个参数的系数")
    return fixed_count

if __name__ == "__main__":
    file_path = sys.argv[1] if len(sys.argv) > 1 else "/Users/yangyang/Desktop/code/ems-cpp-v1/config/protocols/monet/iot_template.json"
    fix_coefficients(file_path)